'use strict';

/* Controllers */

angular.module('app')
  .controller('AppCtrl', ['$scope', '$rootScope', '$translate', '$localStorage', '$window', '$http','$state', 'dialogs', '$sessionStorage',
    function($scope, $rootScope,  $translate,   $localStorage,   $window, $http, $state, dialogs, $sessionStorage) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');

      // config
      $scope.app = {
        name: '综合信息管理',
        version: '1.4.7',
        // for chart colors
        color: {
          primary: '#7266ba',
          info:    '#23b7e5',
          success: '#27c24c',
          warning: '#fad733',
          danger:  '#f05050',
          light:   '#e8eff0',
          dark:    '#3a3f51',
          black:   '#1c2b36'
        },
        settings: {
          themeID: 8,
          navbarHeaderColor: 'bg-info dker',
          navbarCollapseColor: 'bg-info dker',
          asideColor: 'bg-light dker b-r',
          headerFixed: true,
          asideFixed: false,
          asideFolded: false,
          asideDock: false,
          container: false
        }
      }

      // save settings to local storage
      if ( angular.isDefined($localStorage.settings) ) {
        $scope.app.settings = $localStorage.settings;
      } else {
        $localStorage.settings = $scope.app.settings;
      }
      $scope.$watch('app.settings', function(){
        if( $scope.app.settings.asideDock  &&  $scope.app.settings.asideFixed ){
          // aside dock and fixed must set the header fixed.
          $scope.app.settings.headerFixed = true;
        }
        // save to local storage
        $localStorage.settings = $scope.app.settings;
      }, true);

      // angular translate
      $scope.lang = { isopen: false, center_line_name : 'zh-CN', name : 'zh-CN' };
      $scope.langs = {zh_CN:'中文', en:'English'};
      $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "中文";
      $scope.setLang = function(langKey, $event) {
        // set the current lang
        $scope.selectLang = $scope.langs[langKey];
        $scope.lang.center_line_name = langKey.replace('_', '-');
        $scope.lang.name = langKey;
        // You can change the language during runtime
        $translate.use(langKey);
        $scope.lang.isopen = !$scope.lang.isopen;
      };

      function isSmartDevice( $window ) {
          // Adapted from http://www.detectmobilebrowsers.com
          var ua = $window['navigator']['userAgent'] || $window['navigator']['module'] || $window['opera'];
          // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
          return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
      }

      $rootScope.hasPermission = function(permission) {
          if($rootScope.authorities) {
              for(var i = 0; i < $rootScope.authorities.length; i++) {
                  var auth = $rootScope.authorities[i];
                  if(permission === auth.authority) {
                      return true;
                  }
              }
          }
          return false;
      }

      $http.get('index.do').success(function (res) {
        $rootScope.main = res.entity;
        if(res.entity) {
            $rootScope.authorities = res.entity.authorities;
        }
      });

      $rootScope.dictionaryConfig = function(tmp){
        var ds = {};
        // 组装数据字典
        for(var i = 0; i < tmp.length; i++) {
          if(!ds[tmp[i].type]) {
            ds[tmp[i].type] = [];
          }
          var dvalue = tmp[i].value;
          if(tmp[i].dataType == 'boolean') {
            dvalue = ('true' === dvalue ? true : false);
          } else if(tmp[i].dataType == 'int'){
            dvalue = parseInt(dvalue);
          }
          ds[tmp[i].type].push({
            "label": tmp[i].label,
            "value": dvalue
          });
        }

        $rootScope.dictionary =ds;
      }

      // 数据字典部分

      var tmp = [];
      if(!$sessionStorage['sys_dictionary']) {
        $http.get('system/dictionary/listAll.do').success(function (res) {
          $sessionStorage['sys_dictionary'] = res.data;
          $rootScope.dictionaryConfig(res.data);
        });
      } else {
          $rootScope.dictionaryConfig($sessionStorage['sys_dictionary']);
      }

      $scope.openChanagePwd = function () {
          dialogs.create('tpl\/blocks\/changePWD.html','changePWDCtrl',null,{size:'md',keyboard: true,backdrop: true,windowClass: 'my-class'});
      }

//      $rootScope.login = function(){
//        dialogs.create('system-tpl\/login.html','loginFormController',null,{size:'md',keyboard: true,backdrop: true,windowClass: 'my-class'});
//      }
      $rootScope.loginout = function(){
    	  $http.get('j_spring_security_logout').success(function (res) {
    		 if(res.success) {
    			 $state.go('access.login');
    		 }
	      });

      }

    }]);

app.controller('changePWDCtrl',['$scope', '$uibModalInstance','data','httpWrapService','dialogs', function($scope,$uibModalInstance,data, httpWrapService,dialogs){
  $scope.data = {

  };


  $scope.cancel = function(){
    $uibModalInstance.dismiss('Canceled');
  }; // end cancel

  $scope.ok = function(){
    httpWrapService.post('changePWD.do', {
      password : $scope.password
    }).then(function(){
      $uibModalInstance.close();
      dialogs.notify('信息', '修改成功', {size : 'sm'});
    }, function(){
      dialogs.notify('错误', '修改失败', {size : 'sm'});
    });

  };

}]); // end controller(customDialogCtrl)


/* Controllers */
// signin controller
//app.controller('loginFormController', ['$scope', '$modalInstance','data', function ($scope,$modalInstance,data) {
//  $scope.cancel = function(){
//    $modalInstance.dismiss('Canceled');
//  }; // end cancel
//
//  $scope.login = function () {
//    $scope.auth = {};
//    $scope.auth.msg = null;
//    $scope.auth.buttonDisable = true;
//    // Try to login
//    $.post('j_spring_security_check', {
//          username: $scope.username,
//          password: $scope.password
//        },
//        function (data) {
//          if (data.success) {
//            $modalInstance.close();
//          } else {
//            $scope.auth.msg = data.msg;
//            $scope.auth.buttonDisable = false;
//            $scope.$apply();
//          }
//        }, "json");
//  };
//}])
//;